<template>
  <el-dialog :model-value="props.show" :title="`${title}渠道`" width="440px" :before-close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="渠道名称" prop="name">
        <el-input style="width: 80%;" v-model="form.name" placeholder="请输入"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="loading" @click="handleClose">取消</el-button>
        <el-button :loading="loading" type="primary" @click="confirm(formRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { useTableRefresh } from '@/hooks/index';
import { useCommonData } from '../Hooks/index'
import { addChannel } from '@/api/Member/index'
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  detail: {
    type: Object,
    default: () => ({ }),
  },
});
const isEdit = computed(() => {
  return Object.keys(props.detail).length > 0;
});
const title = computed(() => {
  return isEdit.value ? '编辑' : '新增';
});
const { seachTableRef } = useCommonData();

const rules = ref({
  name: [
    { required: true, message: '请输入渠道名称', trigger: 'blur' },
  ],
});
const form = ref({
  name: '',
});
watch(() => props.detail, (val) => {
  if (Object.keys(val).length > 0) {
    form.value.name = val.sourceChannel;
  }else{
    form.value.name = '';
  }
},{
  deep: true,
});


const loading = ref(false);
const formRef = ref();
const confirm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    try{
      loading.value = true;
      if (!valid) return;
      const params = {
        sourceChannel: form.value.name,
      };
      if (isEdit.value) {
        params.id = props.detail.id;
      }
      await addChannel(params);
      handleClose();
      ElMessage.success(`${title.value}成功`);
      useTableRefresh(seachTableRef, isEdit.value);
    }finally{
      loading.value = false;
    }
  });
}

const emit = defineEmits(['close']);
const handleClose = () => {
  emit('close', false);
};
</script>

<style lang="less" scoped>
.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>